﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhoneBilling.Models;
using System.Text;

namespace PhoneBilling.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Login()
        {
            LoginModel model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    User user = (from u in entities.User
                                 where u.Name.Trim() == model.UserName
                                 select u).SingleOrDefault();
                    if (user == null)
                        ModelState.AddModelError("", "没有这个用户");
                    else if (user.Password.Trim() != model.Password)
                        ModelState.AddModelError("", "密码不正确");

                    if (!ModelState.IsValid)
                        return View(model);

                    MenuModel menuModel = new MenuModel();
                    menuModel.Load();
                    Session["Menu"] = menuModel;
                    Session["User"] = model.UserName;
                    Session["UserID"] = user.ID;

                    return this.RedirectToAction("Index", "Manage");
                }
                return View(model);
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach(var ee in ex.LoaderExceptions)
                    sb.AppendLine(ee.Message);
                throw new Exception(sb.ToString());
            } 
        }

        public ActionResult Logout()
        {
            Session["Menu"] = null;
            Session["User"] = null;
            return this.RedirectToAction("../Account/Login");
        }

    }
}
